package com.miracle.core.aspect;

import com.miracle.common.utils.SecurityUtils;
import com.miracle.common.utils.StringUtils;
import com.miracle.core.security.domain.SecurityUserDetails;
import com.miracle.system.domain.SysOperatelog;
import com.miracle.system.domain.SysUser;
import com.miracle.system.service.SysOperatelogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.Signature;

/**
 * @author ：miracle.cui
 * @description：TODO
 * @date ：2020/7/22 11:15
 */
@Aspect
@Component
public class LogAspect {
    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Autowired
    SysOperatelogService operatelogService;

    // 配置织入点
    @Pointcut("execution(* com.miracle.system.web.*.*(..)) && !target(com.miracle.system.web.SysOperatelogController)")
    public void logAspect() {}

    @Before(value = "logAspect()")
    public void doBefore(JoinPoint joinPoint)
    {
        logger.info("#####################    aop doBefore()     ####################");
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(value = "logAspect()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult)
    {
        logger.info("#####################    aop doAfterReturning()     ####################");
       // handleLog(joinPoint, null, jsonResult);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        logger.info("IP: " + request.getRemoteAddr());
        logger.info("URL: " + request.getRequestURL().toString());
        SecurityUserDetails user = SecurityUtils.getUserDetails();
        Integer userId = SecurityUtils.getUserId();
        if (userId != null){

            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            String className = StringUtils.substringAfterLast(
                    signature.getDeclaringTypeName(), ".");

            // 方法路径
            String methodName = joinPoint.getTarget().getClass().getName() + "." + signature.getName() + "()";
            SysOperatelog operatelog = new SysOperatelog();

            operatelog.setCreateBy(userId);
            operatelog.setUserId(userId);
            operatelog.setOperateType(signature.getName());
            operatelog.setLogDesc(methodName);
            operatelogService.insertOperatelog(operatelog);
        }
    }
}
